<?php

namespace Admin\Logic;

use Common\Model\ContractModel;

class ContractLogic extends ContractModel 
{

	protected function _initialize() 
	{
		parent::_initialize();
	}

	public function getPage($where = array(), &$pageShow = null, $pageSize = 10, $parameter = array()) 
	{	
		
		$where['start_time'] = empty($where['start_time']) == false ? $where['start_time']:'2017-01-01';
		
		$where['end_time'] = empty($where['end_time']) == false ? $where['end_time'] : date("Y-m-d H:i:s",time());
			
		$sql .= 'contract_time BETWEEN ' . strtotime($where["start_time"]) . ' AND ' . (strtotime($where["end_time"])+86400);
		
		if($where['status'] !== 'all')
		{
			$sql .= ' AND contract_status = ' . I('get.status');
		}
		
		$sql .= empty($where['name']) ? '':' AND ('.sprintf('LOCATE("%1$s",contract_name)',$where['name']).')';
		
		$sql .= empty($where['number']) ? '':' AND ('.sprintf('LOCATE("%1$s",contract_number)',$where['number']).')';
		
		$sql .= empty($where['cardid']) ? '':' AND ('.sprintf('LOCATE("%1$s",contract_cardid)',$where['cardid']).')';
		
		$sql .= empty($where['transaction_id']) ? '':' AND ('.sprintf('LOCATE("%1$s",contract_transaction_id)',$where['transaction_id']).')';
		
		$totalRows = $this->where($sql)->count();
		
		$order = 'contract_time DESC,contract_id DESC';
		
		$data = $this->where($sql)->pagination($totalRows, $pageShow, $pageSize, $parameter)->order($order)->getItems();

		foreach ($data as $key => &$item) 
		{
			$item['status'] = get_format_state($item['contract_status'],array('未支付','支付成功.text-green','支付失败.text-red'));
			$item['time'] = get_format_date($item['contract_time']);
			$item['amount']  = get_format_money($item['contract_amount']/100);
			$item['edit'] = get_format_url('edit', $item['contract_id']);
			$item['delete'] = get_format_url('delete', $item['contract_id']);
		}

		return $data;
	}

	public function updateContract($data = array()) 
	{
		$map = array(
			'status' => 0,
		);
		
		$data = completion($data, $map);

		return $this->updateByPK($data);
	}

	public function getEdit($pk = 0) 
	{
		return $this->getItem($pk);
	}

	public function updateByPK($data = array()) 
	{
		$data = $this->create($data);
		return $this->updateRecord($data);
	}

	public function deleteByPK($pk = 0) 
	{
		return $this->deleteRecord($pk);
	}
	
	public function getAllStatus()
	{
		return array(
				1=>'支付成功',
				0=>'未支付',
				2=>'支付失败',
		);
	}

}


